package com.dsg.service.apply.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.dao.apply.DsgApplyCarMapper;
import com.dsg.entity.apply.*;
import com.dsg.entity.dto.RejectCarDto;
import com.dsg.entity.dto.ReturnCardRecordDto;
import com.dsg.service.DsgServiceImpl;
import com.dsg.service.apply.IDsgApplyCarService;
import com.dsg.service.apply.IDsgApplyCardService;
import com.dsg.service.apply.IDsgApplyResultService;
import com.dsg.service.apply.IDsgApplyStatusService;
import com.dsg.service.oil.IDsgOilDataDetailService;
import com.dsg.service.set.IDsgSetCarBacklistService;
import com.dsg.service.task.IDsgTaskProcallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 車輛資料 服务实现类
 * </p>
 *
 * @author system
 * @since 2020-07-04
 */
@Slf4j
@Service
public class DsgApplyCarServiceImpl extends DsgServiceImpl<DsgApplyCarMapper, DsgApplyCar> implements IDsgApplyCarService {
    @Autowired
    IDsgApplyStatusService statusService;
    @Autowired
    IDsgSetCarBacklistService carBacklistService;
    @Autowired
    private IDsgApplyCardService cardService;
    @Autowired
    IDsgApplyResultService resultService;
    @Autowired
    IDsgTaskProcallService procallService;
    @Autowired
    IDsgOilDataDetailService oilDataDetailService;

    @Override
    public Page<RejectCarDto> selectRejectCar(Page<RejectCarDto> page, DsgApplyCar en) {
        return baseMapper.selectRejectCar(page, en);
    }

    @Override
    public List<DsgApplyCar> selectCar(String cusNo) {
        return baseMapper.selectCar(cusNo);
    }

    @Override
    public void removeAddress(String carOid) {
        baseMapper.removeAddress(carOid);
    }

    @Override
    public boolean carAuditAll(DsgApplyBill bill) throws Exception {
        boolean oneCarPass = false;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", bill.getAppNo());
        wrapper.eq("CAR_STATUS", DsgApplyCar.CAR_STATUS_RECORD);
        List<DsgApplyCar> carList = list(wrapper);
        if (CollectionUtil.isNotEmpty(carList)) {
            log.info("审核的车辆数：" + carList.size());
            for (DsgApplyCar car : carList) {
                oneCarPass = audit(bill, car) || oneCarPass;
            }
        }

        return oneCarPass;
    }

    @Override
    public boolean rebornCarAudi(DsgApplyBill bill, List<DsgApplyCar> carList) throws Exception {
        boolean oneCarPass = false;
        if (CollectionUtil.isNotEmpty(carList)) {
            log.info("审核的车辆数：" + carList.size());
            for (DsgApplyCar car : carList) {
                oneCarPass = audit(bill, car) || oneCarPass;
            }
        }
        return oneCarPass;
    }

    @Override
    public boolean audit(DsgApplyBill bill, DsgApplyCar car) throws Exception {
        boolean pass = false;
        String reason = null;

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("RESULT_TYPE", DsgApplyResult.RESULT_TYPE_CAR);
        wrapper.eq("RESULT_NAME", car.getCarNo());
        wrapper.eq("APP_NO", bill.getAppNo());
        DsgApplyResult result = resultService.getOne(wrapper);
        if (result != null && result.getResultStatus() == DsgApplyResult.RESULT_STATUS_FORCE) {
            return true;
        }

        wrapper = new QueryWrapper();
        wrapper.eq("CAR_NO", car.getCarNo());
        wrapper.eq("CUS_NO", car.getCusNo());
        wrapper.ne("OID", car.getOid());
        DsgApplyCar dupCar = getOne(wrapper, false);
        if (dupCar == null) {
            wrapper = new QueryWrapper();
            wrapper.eq("APP_NO", bill.getAppNo());
            List<DsgApplyCar> carList = list(wrapper);
            if (carList.size() == 1) {//一单一车
                if (!car.getCarType().equals(DsgApplyCar.CAR_TYPE_MOBILE)) {
                    pass = true;
                } else {
                    reason = "電單車";
                }
            } else {
                pass = true;
            }
        } else {
            wrapper = new QueryWrapper();
            wrapper.eq("CAR_NO", car.getCarNo());
            if (carBacklistService.count(wrapper) == 0) {
                if (!dupCard(bill, car)) {
                    pass = true;
                }
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                Date bookRegDate = car.getBookRegDate();
                bookRegDate = sdf.parse(sdf.format(bookRegDate));
                Date _20160301 = sdf.parse("20160301");
                if (bookRegDate.after(_20160301)) {
                    if (!dupCard(bill, car)) {
                        pass = true;
                    }
                } else {
                    reason = "提供牌薄登記為16年3月1日之前";
                }
            }

            if (reason == null && !pass) {
                if (bill.getKeepType().equals(DsgApplyBill.KEEP_TYPE_CASH)) {
                    //是否達標
                    if (isUpToStandard(car.getCarNo()))
                        pass = true;
                    else
                        reason = "DUP油卡且不達標";
                } else {
                    reason = "DUP油卡";
                }
            }
        }

        if (result == null) {
            result = new DsgApplyResult();
            result.setOid(UUIDGenerator.getUUID());
            result.setResultType(DsgApplyResult.RESULT_TYPE_CAR);
            result.setResultName(car.getCarNo());
            result.setAppNo(bill.getAppNo());
        }
        result.setResultReason(reason);
        if (pass) {
            result.setResultStatus(DsgApplyResult.RESULT_STATUS_SUCCESS);
        } else {
            result.setResultStatus(DsgApplyResult.RESULT_STATUS_FAIL);
        }
        resultService.saveOrUpdate(result);

        wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", car.getAppNo());
        wrapper.eq("CAR_NO", car.getCarNo());
        List<DsgApplyStatus> statuses = statusService.list(wrapper);
        statuses.forEach(e -> {
            e.setIsAuditCar(DsgApplyStatus.IS_AUDIT_YES);
            e.setAppStatus(bill.getAppStatus());
        });
        statusService.updateBatchById(statuses);

        return pass;
    }

    /**
     * 根据车牌号检查入油数据明细表，如果4个月内有使用过油咭加油则不通过
     * 判断4个月内是否有做过推广，如果有则不通过
     * @param carNo
     * @return
     */
    boolean isUpToStandard(String carNo) {
        if (procallService.selectByCar(carNo) == null && oilDataDetailService.selectByCar(carNo) == null)
            return true;
        else
            return false;
    }

    /**
     * DUP能源卡
     *
     * @return
     */
    private boolean dupCard(DsgApplyBill bill, DsgApplyCar car) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("CAR_ID", car.getOid());
        List<DsgApplyCard> cardList = cardService.list(wrapper);

        boolean isDup = false;
        for (DsgApplyCard card :
                cardList) {
            DsgApplyCard dupCard = null;
            if(bill.getKeepType().equals(DsgApplyBill.KEEP_TYPE_BOOK)) {
                dupCard = cardService.getDupCardBook(car, card.getCardType(), card.getOid());
            } else {
                dupCard = cardService.getDupCardCash(car, card.getCardType(), card.getOid());
            }
            if (dupCard != null) {
                return true;
            }
        }
        return isDup;
    }

    @Override
    public List<DsgApplyCar> selectCarListByBill(String appNo) {
        return baseMapper.selectCarListByBill(appNo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCarAndOther(String oid) {
        return baseMapper.deleteCarAndOther(oid);
    }

    @Override
    public DsgApplyCar detail(String id) {
        return baseMapper.detail(id);
    }

    @Override
    public List<DsgApplyCar> selectDsgApplyCarAndCard(DsgApplyCar dsgApplyCar) {
        return baseMapper.selectDsgApplyCarAndCard(dsgApplyCar);
    }

    @Override
    public Page<DsgApplyCar> selectDsgApplyCarList(Page<DsgApplyCar> page, DsgApplyCar dsgApplyCar) {
        dsgApplyCar.setUserId(SingletonLoginUtils.getSystemUserId());
        return page.setRecords(baseMapper.selectDsgApplyCarList(page, dsgApplyCar));
    }

    @Override
    public List<DsgApplyCar> selectDsgApplyCarList(DsgApplyCar dsgApplyCar) {
        return baseMapper.selectDsgApplyCarList(dsgApplyCar);
    }

    @Override
    public Page<ReturnCardRecordDto> selectReturnCardList(Page<ReturnCardRecordDto> page, ReturnCardRecordDto returnCardRecordDto) {
        return page.setRecords(baseMapper.selectReturnCardList(page, returnCardRecordDto));
    }
}
